package com.azunitech.apm.bundles.shell.commands;

import java.io.PrintStream;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import com.azunitech.apm.bundles.shell.BasicCommand;

public class CommandDROP extends BasicCommand<BundleContext>
{
	private static final String CMD_KEY = "drop";
	private static final String CMD_DESC = "uninstall a bundle with bundle id";
	
	public String getKey() 
	{
		return CommandDROP.CMD_KEY;
	}

	public String getDesc() 
	{
		return CommandDROP.CMD_DESC;
	}

	public void exec(String args, PrintStream out, PrintStream err)
			throws Exception 
	{
		BundleContext context = this.m_target;
		if ( args.length() >= 5)
		{
			String id = args.substring(5);
			Bundle bundle = context.getBundle(Long.parseLong(id));
			new SelfUninstallThread(bundle).start();
		}
	}
	
	private static final class SelfUninstallThread extends Thread 
	{
	    private final Bundle m_self;

	    public SelfUninstallThread(Bundle self) 
	    {
	    	super("SelfUpdateThread Bundle " + self.getBundleId());
	    	m_self = self;
	    }

	    public void run() 
	    {
	    	try 
	    	{
	    		m_self.uninstall();
	    	} 
	    	catch (BundleException e) 
	    	{
	    		// Ignore
	    	}
	    }
	}
}

